package com.uphone.kingmall.activity;

import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.china.zhuoyue.R;
import com.google.gson.JsonSyntaxException;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.uphone.kingmall.activity.personal.OtherSettleActivity;
import com.uphone.kingmall.adapter.ShopRecoGoodsAdapter;
import com.uphone.kingmall.app.MyApplication;
import com.uphone.kingmall.base.BaseActivity;
import com.uphone.kingmall.bean.GoodsDetailBean;
import com.uphone.kingmall.bean.GoodsInfoShopInfoBean;
import com.uphone.kingmall.bean.OtherOderBean;
import com.uphone.kingmall.bean.SettleCartBean;
import com.uphone.kingmall.bean.ShopRecoGoodsBean;
import com.uphone.kingmall.bean.UserInfosBean;
import com.uphone.kingmall.dialog.ShopCartPw;
import com.uphone.kingmall.listener.onNormalRequestListener;
import com.uphone.kingmall.login.LoginActivity;
import com.uphone.kingmall.main.MainActivity;
import com.uphone.kingmall.utils.ActivityCollector;
import com.uphone.kingmall.utils.CommonUtil;
import com.uphone.kingmall.utils.ConstansUtils;
import com.uphone.kingmall.utils.GlideImageLoader;
import com.uphone.kingmall.utils.GlideUtils;
import com.uphone.kingmall.utils.GsonUtils;
import com.uphone.kingmall.utils.MyUrl;
import com.uphone.kingmall.utils.OkGoUtils;
import com.uphone.kingmall.utils.RatingBar;
import com.uphone.kingmall.utils.SharedPreferencesHelper;
import com.uphone.kingmall.utils.ToastUtils;
import com.uphone.kingmall.utils.intent.IntentData;
import com.uphone.kingmall.utils.intent.IntentUtils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
//import io.rong.imkit.RongIM;
//import io.rong.imlib.model.CSCustomServiceInfo;

/**
 * author : SuMeng
 * e-mail : 986335838@qq.com
 * time   : 2019/02/21
 * desc   : 商品详情页面
 */
public class GoodsDetailActivity extends BaseActivity {
    @BindView(R.id.banner_view)
    Banner bannerView;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.tv_kuaidifei)
    TextView tvKuaidifei;
    @BindView(R.id.tv_xiaoliang)
    TextView tvXiaoliang;
    @BindView(R.id.tv_stock)
    TextView tvStock;
    @BindView(R.id.tv_guige)
    TextView tvGuige;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_youhui)
    TextView tvYouhui;
    @BindView(R.id.tv_zuiduo_dikou)
    TextView tvZuiduoDikou;
    @BindView(R.id.tv_jifen_dikou)
    TextView tvJifenDikou;
    @BindView(R.id.tv_jifen_kedi)
    TextView tvJifenKedi;
    @BindView(R.id.rl_youhui)
    RelativeLayout rlYouhui;
    @BindView(R.id.tv_pingjia_num)
    TextView tvPingjiaNum;
    @BindView(R.id.tv_all_pingjia)
    TextView tvAllPingjia;
    @BindView(R.id.iv_shop_icon)
    ImageView ivShopIcon;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.ll_starview)
    LinearLayout llStarview;
    @BindView(R.id.tv_lianxi_shangjia)
    TextView tvLianxiShangjia;
    @BindView(R.id.tv_jinru_dianpu)
    TextView tvJinruDianpu;
    @BindView(R.id.ll_shoucangjia)
    LinearLayout llShoucangjia;
    @BindView(R.id.ll_guanzhu)
    LinearLayout llGuanzhu;
    @BindView(R.id.ll_zuji)
    LinearLayout llZuji;
    @BindView(R.id.tv_gouwuche)
    TextView tvGouwuche;
    @BindView(R.id.tv_kefu)
    TextView tvKefu;
    @BindView(R.id.tv_shoucang)
    TextView tvShoucang;
    @BindView(R.id.tv_home)
    TextView tvHome;
    @BindView(R.id.tv_jiaru_gouwuche)
    TextView tvJiaruGouwuche;
    @BindView(R.id.tv_lijigoumai)
    TextView tvLijigoumai;
    @BindView(R.id.ll_web)
    LinearLayout mLlWeb;
    @BindView(R.id.tv_shop_fans)
    TextView tvShopFans;
    @BindView(R.id.tv_shop_goods_num)
    TextView tvShopGoodsNum;
    @BindView(R.id.tv_shop_sale_num)
    TextView tvShopSaleNum;
    @BindView(R.id.rv_commend)
    RecyclerView rvCommend;
    @BindView(R.id.ll_commend)
    LinearLayout llCommend;
    @BindView(R.id.rb_shop)
    RatingBar rbShop;
    @BindView(R.id.ll_shop)
    LinearLayout llShop;
    @BindView(R.id.tv_share)
    TextView tvShare;
    @BindView(R.id.content_detail)
    RelativeLayout contentDetail;
    private ShopCartPw shopCartPw;
    @IntentData
    private int id = -1;
    @IntentData
    int type = TYPE_GOODS;
    public static final int TYPE_GOODS = 0X0011;//商品详情
    public static final int TYPE_HAGGLE = 0X0022;//砍价购
    public static final int TYPE_FLASH = 0X0033;//限时购
    public static final int TYPE_ADVERTS = 0X0044;//首页顶部广告轮播图关联的后台直接添加的商品
    private GoodsDetailBean bean;
    private GoodsInfoShopInfoBean shopBean;
    List<ShopRecoGoodsBean.RecoGoodsBean> recoList = new ArrayList<>();
    private ShopRecoGoodsAdapter recoGoodsAdapter;
    private boolean isWeb = false;

    @Override
    public int getLayoutContentId() {
        return R.layout.kingmall_activity_goods_detail;
    }

    @Override
    public void initView() {
        LogUtils.e("type:" + type);
        Intent mgetvalue = getIntent();
        String maction = mgetvalue.getAction();
        if (Intent.ACTION_VIEW.equals(maction)) {
            Uri uri = mgetvalue.getData();
            if (uri != null) {
                String webId = uri.getQueryParameter("id");
                String webType = uri.getQueryParameter("type");
                LogUtils.e("webId:" + webId + "    type:" + type);
                if (!TextUtils.isEmpty(webId)) {
                    try {
                        id = Integer.parseInt(webId);
                        isWeb = true;
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }
                if (!TextUtils.isEmpty(webType)) {
                    try {
                        type = Integer.parseInt(webType);
                        LogUtils.e("type:web" + type);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        LogUtils.e("id:" + id);
        LogUtils.e("type:" + type);
        setStatusBar();
        switch (type) {
            case TYPE_GOODS:
                llShop.setVisibility(View.VISIBLE);
                tvJiaruGouwuche.setVisibility(View.VISIBLE);
                tvLijigoumai.setText("立即购买");
                tvGouwuche.setVisibility(View.VISIBLE);
                tvShoucang.setVisibility(View.VISIBLE);
                tvHome.setVisibility(View.GONE);
                rlYouhui.setVisibility(View.VISIBLE);
                tvShare.setVisibility(View.VISIBLE);
                break;
            case TYPE_HAGGLE:
                llShop.setVisibility(View.GONE);
                tvJiaruGouwuche.setVisibility(View.GONE);
                tvLijigoumai.setText("我要砍价");
                tvGouwuche.setVisibility(View.GONE);
                tvShoucang.setVisibility(View.GONE);
                tvHome.setVisibility(View.VISIBLE);
                rlYouhui.setVisibility(View.GONE);
                tvShare.setVisibility(View.VISIBLE);
                break;
            case TYPE_FLASH:
                llShop.setVisibility(View.GONE);
                tvJiaruGouwuche.setVisibility(View.GONE);
                tvLijigoumai.setText("立即抢购");
                tvGouwuche.setVisibility(View.GONE);
                tvShoucang.setVisibility(View.GONE);
                tvHome.setVisibility(View.VISIBLE);
                rlYouhui.setVisibility(View.GONE);
                tvShare.setVisibility(View.VISIBLE);
                break;
            case TYPE_ADVERTS:
                llShop.setVisibility(View.GONE);
                tvGouwuche.setVisibility(View.VISIBLE);
                tvShoucang.setVisibility(View.VISIBLE);
                tvHome.setVisibility(View.GONE);
                rlYouhui.setVisibility(View.VISIBLE);
                tvShare.setVisibility(View.GONE);
                break;
        }

    }

    private void loadCommend() {

//        LinearLayoutManager manager = new LinearLayoutManager(this);
//        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvCommend.setLayoutManager(new GridLayoutManager(this, 2));
        recoGoodsAdapter = new ShopRecoGoodsAdapter();
        rvCommend.setAdapter(recoGoodsAdapter);
        mLlWeb.setMinimumHeight(MyApplication.height);
        recoGoodsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                CommonUtil.startIntent(GoodsDetailActivity.this, GoodsDetailActivity.class, recoList.get(position).getGoodsId());
            }
        });

        HttpParams params = new HttpParams();
        params.put("goodsId", id);
        //获取推荐商品
        OkGoUtils.normalRequest(MyUrl.getShopRecoGoods, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                ShopRecoGoodsBean bean = GsonUtils.getGson().fromJson(body, ShopRecoGoodsBean.class);
                if (bean.getCode() == 0) {
                    recoList.clear();
                    if (bean.getRecoGoods() != null) {
                        recoList.addAll(bean.getRecoGoods());
                    }
                    recoGoodsAdapter.setNewData(recoList);
                }

            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    @Override
    public void initData() {
        HttpParams params = new HttpParams();
        params.put("goodsId", id);

        //获取商品详情
        OkGoUtils.progressRequest(MyUrl.getGoodsInfo, this, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                bean = GsonUtils.getGson().fromJson(body, GoodsDetailBean.class);
                loadData();

            }

            @Override
            public void onError(Response<String> response) {

            }
        });


    }

    private List<GoodsDetailBean.GoodsBean.PropsBean.PropBean> goodPropList;

    /**
     * 1 加入购物车 2规格
     */
    private void openCartList(final String type2) {

        if (bean == null || bean.getGoods() == null) {
            ToastUtils.showShortToast(this, "未找到商品");
            return;
        }
        if (bean.getGoods().getGoodsType() != 3 && bean.getGoods().getGoodsType() != 4 && bean.getGoods().getRepertoryNum() <= 0) {
            ToastUtils.showShortToast(this, "库存不足");
            return;
        }
        shopCartPw = new ShopCartPw(GoodsDetailActivity.this, bean.getGoods(), goodPropList, new ShopCartPw.setOnDialogClickListener() {

            @Override
            public void onClick(View v, int type, String pos, String num, String price) {
                switch (v.getId()) {
                    case R.id.pw_cart_btn://确定
                        break;
                }
            }

            @Override
            public void onClick(View v, int type, List<GoodsDetailBean.GoodsBean.PropsBean> propsList, List<GoodsDetailBean.GoodsBean.PropsBean.PropBean> propList, String num, String price) {
                switch (v.getId()) {
                    case R.id.pw_cart_btn://确定
                        if (type == 666) {
                            if (type2.equals("0")) {
                                //立即购买
                                if (GoodsDetailActivity.this.type == TYPE_HAGGLE) {
                                    //发起砍价
                                    launchHaggle(propList, price, num);
                                    return;
                                } else if (GoodsDetailActivity.this.type == TYPE_FLASH) {
                                    otherSumit(propList, price, num);
                                    return;
                                }
                                settle(propList, num, price);
                            }
                            if (type2.equals("1")) {
                                //加入购物车
                                addShoppingCart(propList, num);
                            } else {
                                //规格
                                goodPropList = propList;
                                String propNames = "";
                                for (int i = 0; i < propList.size(); i++) {
                                    propNames += propList.get(i).getGoodsPropVal() + " ";
                                }
                                tvGuige.setText("规格  " + propNames);
                            }
                        }
                        break;
                }
            }
        }, new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setStatusBar();
            }

        });
        shopCartPw.showAtLocation(shopCartPw.popupView.getRootView(), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    private void settle(List<GoodsDetailBean.GoodsBean.PropsBean.PropBean> propList, String num, String price) {
        HttpParams params = new HttpParams();
        params.put("goodsId", id);
        params.put("goodsNum", num);
        String propIds = "";
        for (int i = 0; i < propList.size(); i++) {
            propIds += propList.get(i).getGoodsPropId() + ",";
        }
        if (propIds.length() > 1) {
            params.put("goodsPropId", propIds.substring(0, propIds.length() - 1));
        }
        OkGoUtils.progressRequest(MyUrl.goodsBalancePage, this, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                if (code == 0) {
                    try {
                        JSONObject jsonObject = new JSONObject(body);
                        String result = jsonObject.getString("result");
                        SettleCartBean.ShopGoodsBean shopGoodsBean = GsonUtils.getGson().fromJson(result, SettleCartBean.ShopGoodsBean.class);
                        List<SettleCartBean.ShopGoodsBean.GoodsBean> goodsList = new ArrayList<>();
                        goodsList.add(shopGoodsBean.getGoodsInfo());
                        shopGoodsBean.setGoods(goodsList);
                        SettleCartBean settleCartBean = new SettleCartBean();
                        settleCartBean.setCode(41);
                        settleCartBean.setTotalFee(shopGoodsBean.getSumGoodsFee());
                        ArrayList<SettleCartBean.ShopGoodsBean> list = new ArrayList<>();
                        list.add(shopGoodsBean);
                        settleCartBean.setShopGoods(list);
                        String settleData = GsonUtils.getGson().toJson(settleCartBean);
                        IntentUtils.getInstance()
                                .with(GoodsDetailActivity.this, SettleActivity.class)
                                .putString(ConstansUtils.JSON_STR, settleData).start();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    private void addShoppingCart(List<GoodsDetailBean.GoodsBean.PropsBean.PropBean> propList, String num) {
        HttpParams params = new HttpParams();
        params.put("goodsId", id);
        if (propList != null) {
            String goodsPropIds = "";
            for (int i = 0; i < propList.size(); i++) {
                goodsPropIds += propList.get(i).getGoodsPropId() + ",";
            }
            if (!TextUtils.isEmpty(goodsPropIds)) {
                String str = goodsPropIds.substring(0, goodsPropIds.length() - 1);
                params.put("goodsPropIds", str);
            }
        }
        params.put("goodsNum", num);
        OkGoUtils.progressRequest(MyUrl.addShopCar, this, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String response, int code) {
                if (code == 0) {
                    ToastUtils.showShortToast(GoodsDetailActivity.this, "成功加入购物车！");
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    private void launchHaggle(final List<GoodsDetailBean.GoodsBean.PropsBean.PropBean> propList, final String price, final String num) {
        HttpParams params = new HttpParams();
        params.put("goodsId", id);

        if (propList != null) {
            String goodsPropIds = "";
            for (int i = 0; i < propList.size(); i++) {
                goodsPropIds += propList.get(i).getGoodsPropId() + ",";
            }
            if (!TextUtils.isEmpty(goodsPropIds)) {
                String str = goodsPropIds.substring(0, goodsPropIds.length() - 1);
                params.put("goodsPropId", str);
            }
        }
        OkGoUtils.progressRequest(MyUrl.launchHaggle, this, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String response, int code) {
                if (code == 0 || code == 1) {
                    if (code == 0) {
                        ToastUtils.showShortToast(GoodsDetailActivity.this, "成功发起砍价");
                    }
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        int haggleId = jsonObject.getInt("haggleId");
                        LogUtils.e("haggleId:" + haggleId);
                        CommonUtil.startIntent(GoodsDetailActivity.this, HaggleDetailActivity.class, haggleId);
                    } catch (Exception e) {
                        LogUtils.e("异常:" + e.toString());
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    private void otherSumit(List<GoodsDetailBean.GoodsBean.PropsBean.PropBean> propList, String price, String num) {
        OtherOderBean otherOderBean = new OtherOderBean(num, price, this.bean.getGoods(), propList, bean.getGoods().getInstallationFee());
        IntentUtils.getInstance().with(this, OtherSettleActivity.class)
                .putString(ConstansUtils.JSON_STR, GsonUtils.getGson().toJson(otherOderBean)).start();
    }

    @OnClick({R.id.tv_guige, R.id.tv_home, R.id.iv_back, R.id.rl_youhui, R.id.tv_all_pingjia, R.id.tv_lianxi_shangjia,
            R.id.tv_jinru_dianpu, R.id.tv_gouwuche, R.id.tv_kefu, R.id.tv_shoucang, R.id.tv_jiaru_gouwuche, R.id.tv_lijigoumai, R.id.tv_share})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_youhui:
                break;
            case R.id.tv_home:
                //返回首页
                ActivityCollector.removeAll(MainActivity.class);
                finish();
                break;
            case R.id.tv_all_pingjia:
                IntentUtils.getInstance().with(GoodsDetailActivity.this, GoodsAllCommentsListActivity.class)
                        .putInt("num", bean.getGoods().getCommentNum())
                        .putInt(ConstansUtils.ID, id).start();
                break;
            case R.id.tv_lianxi_shangjia:
//                if (shopBean != null && shopBean.getShop() != null && !TextUtils.isEmpty(shopBean.getShop().getShopPhone())) {
//                    DialogUtil.showCallDialog(this, shopBean.getShop().getShopPhone());
//                } else {
//                    //联系商家
//                    CSCustomServiceInfo.Builder csBuilder = new CSCustomServiceInfo.Builder();
//                    final CSCustomServiceInfo csInfo = csBuilder.nickName("融云").build();
//                    RongIM.getInstance().startCustomerServiceChat(this, ConstansUtils.CSCustomServiceId, "", csInfo);
//                }
                break;
            case R.id.tv_jinru_dianpu:
                if (shopBean != null && shopBean.getShop() != null && shopBean.getShop().getShopId() != null) {
                    IntentUtils.getInstance().with(this, ShopDetailActivity.class)
                            .putInt(ConstansUtils.ID, shopBean.getShop().getShopId()).start();
                }
                break;
            case R.id.tv_gouwuche:
                if (CommonUtil.checkLogin()) {
                    CommonUtil.startIntent(this, ShoppingCartActivity.class);
                }
                break;
            case R.id.tv_kefu:
//                if (type == TYPE_ADVERTS || type == TYPE_FLASH || type == TYPE_HAGGLE) {
//                    if (CommonUtil.checkLogin()) {
//                        CSCustomServiceInfo.Builder csBuilder = new CSCustomServiceInfo.Builder();
//                        final CSCustomServiceInfo csInfo = csBuilder.nickName("融云").build();
//                        RongIM.getInstance().startCustomerServiceChat(this, ConstansUtils.CSCustomServiceId, "", csInfo);
//                    }
//                } else {
//                    if (bean != null && bean.getGoods() != null && !TextUtils.isEmpty(bean.getGoods().getShopPhone())) {
//                        DialogUtil.showCallDialog(this, bean.getGoods().getShopPhone());
//                    } else {
//                        //联系商家
//                        CSCustomServiceInfo.Builder csBuilder = new CSCustomServiceInfo.Builder();
//                        final CSCustomServiceInfo csInfo = csBuilder.nickName("融云").build();
//                        RongIM.getInstance().startCustomerServiceChat(this, ConstansUtils.CSCustomServiceId, "", csInfo);
//                    }
//                }
                break;
            case R.id.tv_shoucang:
                if (CommonUtil.checkLogin()) {
                    if (tvShoucang.isSelected()) {
                        //取消收藏
                        unCollect();
                    } else {
                        //收藏
                        collect();
                    }
                }
                break;
            case R.id.tv_jiaru_gouwuche:
                openCartList("1");
                break;
            case R.id.tv_lijigoumai:
                openCartList("0");
                break;
            case R.id.tv_guige:
                openCartList("2");
                break;
            case R.id.iv_back:
                onBackPressed();
                break;
            case R.id.tv_share:
                if (TextUtils.isEmpty(SharedPreferencesHelper.getToken())) {
                    CommonUtil.startIntent(GoodsDetailActivity.this, LoginActivity.class);
                    return;
                }
                getUserInfo();
                break;
        }
    }

    private int inviteCode;

    private void getUserInfo() {
        if (!TextUtils.isEmpty(SharedPreferencesHelper.getToken())) {
            OkGoUtils.normalRequest(MyUrl.getUserInfo, null, new onNormalRequestListener() {
                @Override
                public void onSuccess(String body, int code) {
                    if (code == 0) {
                        try {
                            UserInfosBean userInfosBean = GsonUtils.getGson().fromJson(body, UserInfosBean.class);
                            inviteCode = userInfosBean.getUserInfo().getInviteCode();
                            switch (type) {
                                case TYPE_GOODS:
                                    showSharePop(contentDetail, "http://wechat.91wzsc.com/detail/" + id + "?inviteCode=" + inviteCode, bean.getGoods().getGoodsName(),
                                            "我比对了几家店，发现这家卖的批发价价格，真的好便宜，你快来看看", bean.getGoods().getGoodsMainImg());
                                    break;
                                case TYPE_HAGGLE:
                                    showSharePop(contentDetail, "http://wechat.91wzsc.com/myBargainIndex/" + id + "?", bean.getGoods().getGoodsName(),
                                            "好物价格由你定，帮我砍到0元购吧", bean.getGoods().getGoodsMainImg());
                                    break;
                                case TYPE_FLASH:
                                    showSharePop(contentDetail, "http://wechat.91wzsc.com/detailOther/" + id + "?type=limit&inviteCode=" + inviteCode, bean.getGoods().getGoodsName(),
                                            "本周平台畅销榜前五】【平台精挑严选商品】", bean.getGoods().getGoodsMainImg());
                                    break;
                                case TYPE_ADVERTS:

                                    break;
                            }


                        } catch (JsonSyntaxException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onError(Response<String> response) {

                }
            });
        }
    }


    private void unCollect() {
        HttpParams params = new HttpParams();
        params.put("goodsId", id);
        OkGoUtils.progressRequest(MyUrl.cancleCollectGoods, this, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                if (code == 0) {
                    bean.getGoods().setCollectState(0);
                    tvShoucang.setSelected(false);
                    ToastUtils.showShortToast(GoodsDetailActivity.this, "已取消");
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    private void collect() {
        HttpParams params = new HttpParams();
        params.put("goodsId", id);
        OkGoUtils.progressRequest(MyUrl.collectGoods, this, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                if (code == 0) {
                    bean.getGoods().setCollectState(1);
                    tvShoucang.setSelected(true);
                    ToastUtils.showShortToast(GoodsDetailActivity.this, "收藏成功");
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    //读取方法

    public String getJson(String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = this.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }


    // 商铺信息
    private void loadShopData() {
        if (shopBean != null && shopBean.getShop() != null) {
            GoodsInfoShopInfoBean.ShopBean shop = shopBean.getShop();
            GlideUtils.getInstance().loadCornerImage(this, shop.getShopHeadImg(), SizeUtils.dp2px(8), ivShopIcon);

            tvShopName.setText("" + shop.getShopName());
            if (shop.getShopScore() != null) {
                rbShop.setStar(shop.getShopScore());
            }
            tvShopFans.setText("" + shop.getShopFocusNum());
            tvShopGoodsNum.setText("" + shop.getGoodsNum());
            tvShopSaleNum.setText("" + shop.getOrderNum());
        }
    }

    private void loadData() {
        final GoodsDetailBean.GoodsBean goods = bean.getGoods();
        if (goods != null) {
            switch (goods.getGoodsType()) {
                //	1:普通商品;3限时商品;4砍价商品;5品牌大牌商品
                case 1:
//                    if (type != TYPE_ADVERTS) {
//                    } else {
//                        llShop.setVisibility(View.GONE);
//                    }
                    tvJiaruGouwuche.setVisibility(View.VISIBLE);
                    tvLijigoumai.setText("立即购买");
                    llShop.setVisibility(View.VISIBLE);
                    netShop();
                    tvGouwuche.setVisibility(View.VISIBLE);
                    tvShoucang.setVisibility(View.VISIBLE);
                    tvHome.setVisibility(View.GONE);
                    tvStock.setVisibility(View.VISIBLE);
                    rlYouhui.setVisibility(View.VISIBLE);
                    loadCommend();
                    break;
                case 3:
                    llShop.setVisibility(View.GONE);
                    tvJiaruGouwuche.setVisibility(View.GONE);
                    tvLijigoumai.setText("立即抢购");
                    tvGouwuche.setVisibility(View.GONE);
                    tvShoucang.setVisibility(View.GONE);
                    tvHome.setVisibility(View.VISIBLE);
                    tvStock.setVisibility(View.GONE);
                    rlYouhui.setVisibility(View.GONE);
                    llCommend.setVisibility(View.GONE);
                    type = TYPE_FLASH;
                    break;
                case 4:
                    type = TYPE_HAGGLE;
                    llShop.setVisibility(View.GONE);
                    tvJiaruGouwuche.setVisibility(View.GONE);
                    tvLijigoumai.setText("我要砍价");
                    tvGouwuche.setVisibility(View.GONE);
                    tvShoucang.setVisibility(View.GONE);
                    tvHome.setVisibility(View.VISIBLE);
                    rlYouhui.setVisibility(View.GONE);
                    llCommend.setVisibility(View.GONE);
                    tvStock.setVisibility(View.GONE);
                    break;
                case 5:
//                    if (type != TYPE_ADVERTS) {
//                    } else {
//                        llShop.setVisibility(View.GONE);
//                    }
                    tvJiaruGouwuche.setVisibility(View.VISIBLE);
                    tvLijigoumai.setText("立即购买");
                    llShop.setVisibility(View.VISIBLE);
                    netShop();
                    tvGouwuche.setVisibility(View.VISIBLE);
                    tvShoucang.setVisibility(View.VISIBLE);
                    tvHome.setVisibility(View.GONE);
                    rlYouhui.setVisibility(View.VISIBLE);
                    tvStock.setVisibility(View.VISIBLE);
                    loadCommend();
                    break;
            }
            List<GoodsDetailBean.GoodsBean.ImgsBean> imgs = goods.getImgs();
            if (imgs != null) {
                List<String> strings = new ArrayList<>();
                for (int i = 0; i < imgs.size(); i++) {
                    strings.add(imgs.get(i).getImg());
                }
                initBanner(strings);
            }
            tvPrice.setText("¥" + (goods.getBasePrice() == null ? 0.00 : goods.getBasePrice()));
            tvContent.setText(goods.getGoodsName() + "");
            if (goods.getPostType() == 1) {
                tvKuaidifei.setText("快递:" + (goods.getPostFee() == null ? 0.00 : goods.getPostFee()));
            } else if (goods.getPostType() == 2) {
                tvKuaidifei.setText("仅支持到店消费");
            }
            tvXiaoliang.setText("销量:" + (goods.getGoodsSaleNum()));
            tvStock.setText("库存:" + (goods.getRepertoryNum()));
            if (goods.getYueDeduct() == null) {
                tvZuiduoDikou.setVisibility(View.GONE);
            } else {
                tvZuiduoDikou.setVisibility(View.VISIBLE);
                tvZuiduoDikou.setText(/*goods.getYueDeduct() + */"余额可抵扣" + goods.getYueDeductFee() + "元");
            }
            if (goods.getJiFenDeductFee() == null) {
                tvJifenDikou.setVisibility(View.GONE);
            } else {
                tvJifenDikou.setVisibility(View.GONE);
                tvJifenDikou.setText(/*goods.getYueDeduct() + */"金币可抵扣" + goods.getJiFenDeductFee() + "元");
            }

            tvJifenKedi.setText("您将得到" + goods.getGiveScore() + "金币");
            if (goods.getCollectState() == 0) {
                tvShoucang.setSelected(false);
            } else {
                tvShoucang.setSelected(true);
            }

            tvPingjiaNum.setText("宝贝评价（" + goods.getCommentNum() + "）");
            setUrl(goods.getGoodsDesc());

        }
    }

    private void netShop() {
        HttpParams params = new HttpParams();
        params.put("goodsId", id);
        //获取店铺详情
        OkGoUtils.normalRequest(MyUrl.getGoodsInfoShopInfo, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                shopBean = GsonUtils.getGson().fromJson(body, GoodsInfoShopInfoBean.class);
                loadShopData();
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    public void setUrl(String url) {
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        final WebView webView = new WebView(this);
        mLlWeb.addView(webView, params);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);//开启JavaScript交互
        webSettings.setUseWideViewPort(true);//开启页面自适应屏幕
        webSettings.setLoadWithOverviewMode(true);//
        webSettings.setSupportZoom(false);//关闭双击缩放
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);


//        webSettings.setTextSize(WebSettings.TextSize.LARGEST);
        webSettings.setBuiltInZoomControls(false);//缩放控制条
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//离线缓存功能
        webSettings.setAllowFileAccess(true);//允许跨域访问本地文件
        webSettings.setAppCacheEnabled(true);//允许Web缓存到本地
        webSettings.setDomStorageEnabled(true);//设置DOM Storage缓存
        webSettings.setDatabaseEnabled(true);//允许DataBase存储
        webSettings.setGeolocationEnabled(true);//启用地理定位

//        webSettings.setStandardFontFamily(getResources().getFont().);
//        webSettings.setUserAgentString("User-Agent:PengZhang");
        webSettings.setAllowUniversalAccessFromFileURLs(true);
//        final String dbPath = MyApplication.getInstance().getDir("db", Context.MODE_PRIVATE).getPath();
//        webSettings.setDatabasePath(dbPath);//Storage路径
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);//设置渲染优先级
        webSettings.setPluginState(WebSettings.PluginState.ON);//设置插件状态
        webSettings.setAppCacheEnabled(true);
//        final String cachePath = MyApplication.getInstance().getDir("cache", Context.MODE_PRIVATE).getPath();
//        webSettings.setAppCachePath(cachePath);//cache路径
        webSettings.setAppCacheMaxSize(5 * 1024 * 1024);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(final WebView view, String url) {
                super.onPageFinished(view, url);

                view.post(new Runnable() {
                    @Override
                    public void run() {
                        webView.post(new Runnable() {
                            @Override
                            public void run() {

                                int w = View.MeasureSpec.makeMeasureSpec(0,
                                        View.MeasureSpec.UNSPECIFIED);
                                int h = View.MeasureSpec.makeMeasureSpec(0,
                                        View.MeasureSpec.UNSPECIFIED);
                                // 重新测量
                                webView.measure(w, h);
                            }
                        });
                    }
                });
            }
        });
        webView.loadUrl(url);
    }

    /**
     * 设置banner数据
     */
    private void initBanner(final List<String> topBannerList) {
        List images = new ArrayList<>();
        for (String url : topBannerList) {
            images.add(url);
        }
        //设置图片加载器
        bannerView.setImageLoader(new GlideImageLoader());
        //不显示指示器和标题
        bannerView.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片集合
        bannerView.setImages(images);
        //banner设置方法全部调用完毕时最后调用
        bannerView.start();
        bannerView.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
            }
        });
    }

    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onReceivedTitle(WebView view, String title) {
//            mTvTitle.setText(title);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


}
